import { store } from "@/store";
import { type DictVO, type DictData } from "@/api/system/dict";

export const useDictStore = defineStore("dict", () => {
  const dictionary = useStorage<Record<string, DictData[]>>("dictionary", {});

  const setDictionary = (dict: DictVO) => {
    dictionary.value[dict.dictCode] = dict.dictDataList;
  };

  const loadDictionaries = async () => {
    // const dictList = await DictionaryAPI.getList();
    const dictList = [
      {
        name: "通知级别",
        dictCode: "notice_level",
        dictDataList: [
          {
            value: "0",
            label: "低",
            tagType: "info",
          },
          {
            value: "1",
            label: "中",
            tagType: "warning",
          },
          {
            value: "2",
            label: "高",
            tagType: "danger",
          },
        ],
      },
      {
        name: "通知类型",
        dictCode: "notice_type",
        dictDataList: [
          {
            value: "1",
            label: "系统升级",
            tagType: "success",
          },
          {
            value: "2",
            label: "系统维护",
            tagType: "primary",
          },
          {
            value: "3",
            label: "安全警告",
            tagType: "danger",
          },
          {
            value: "4",
            label: "假期通知",
            tagType: "success",
          },
          {
            value: "5",
            label: "公司新闻",
            tagType: "primary",
          },
          {
            value: "99",
            label: "其他",
            tagType: "info",
          },
        ],
      },
      {
        name: "性别",
        dictCode: "gender",
        dictDataList: [
          {
            value: "1",
            label: "男",
            tagType: "primary",
          },
          {
            value: "2",
            label: "女",
            tagType: "danger",
          },
          {
            value: "0",
            label: "保密",
            tagType: "info",
          },
        ],
      },
    ];

    dictList.forEach(setDictionary);
  };

  const getDictionary = (dictCode: string): DictData[] => {
    return dictionary.value[dictCode] || [];
  };

  const clearDictionaryCache = () => {
    dictionary.value = {};
  };

  const updateDictionaryCache = async () => {
    clearDictionaryCache(); // 先清除旧缓存
    await loadDictionaries(); // 重新加载最新字典数据
  };

  return {
    dictionary,
    setDictionary,
    loadDictionaries,
    getDictionary,
    clearDictionaryCache,
    updateDictionaryCache,
  };
});

export function useDictStoreHook() {
  return useDictStore(store);
}
